package com.czr.dao.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czr.dao.entity.CzrColumn;
import com.czr.dao.entity.CzrNews;
import com.czr.dao.entity.CzrUser;
import com.czr.dao.mapper.CzrNewsMapper;
import com.czr.dao.service.CzrNewsService;
import com.czr.dao.service.CzrUserService;
import com.czr.dto.ColumnParam;
import com.czr.dto.CzrNewsParam;
import com.czr.dto.NewsParam;
import com.czr.dto.Search;
import com.czr.util.DateUtils;
import com.czr.util.PageUtil;
import com.czr.util.TencentCosUtil;
import com.czr.vo.CzrNewsVo;
import com.czr.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 新闻资讯 服务实现类
 * </p>
 *
 */
@Service
public class CzrNewsServiceImpl extends ServiceImpl<CzrNewsMapper, CzrNews> implements CzrNewsService {

    @Autowired
    public CzrNewsMapper czrNewsMapper;

    @Autowired
    public CzrUserService czrUserService;

    @Override
    public Result<Object> list(NewsParam search) throws Exception {
        TencentCosUtil tencentCosUtil=new TencentCosUtil();
        Page<CzrNews> page = new Page<>();
        page.setSize(search.getSize());
        page.setCurrent(search.getCurrent());
        LambdaQueryWrapper<CzrNews> ew = new LambdaQueryWrapper<>();
        if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(search.getKeyword())){
            ew.like(CzrNews::getTitle,search.getKeyword());
        }
        ew.eq(CzrNews::getStatus,1);
        ew.eq(CzrNews::getColumnId,search.getColumnId());

        if(!StringUtils.isEmpty(search.getIsLunbo())){
            ew.eq(CzrNews::getIsLunbo,search.getIsLunbo());
        }
        ew.orderByDesc(CzrNews::getPubTime);
        page = this.getBaseMapper().selectPage(page,ew);
        JSONArray array=new JSONArray();
        for (CzrNews czrNews : page.getRecords()) {
            CzrNewsVo czrNewsVo = new CzrNewsVo();
            BeanUtils.copyProperties(czrNews, czrNewsVo);
            array.add(czrNewsVo);
        }
        JSONObject object= PageUtil.getPage(array,page);
        return Result.data(object);
    }

    @Override
    public Result<Map<String, Object>> addOrUpdate(CzrNewsParam czrNewsParam,Integer userId) throws Exception {
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //验证标题是否存在
        if(StringUtils.isEmpty(czrNewsParam.getId())){
            Map<String,Object> map= czrNewsMapper.getTitle(czrNewsParam.getTitle());
            if(!StringUtils.isEmpty(map)){
                return Result.success(201,"有相同标题新闻资讯，请检查！");
            }
        }
        if(!StringUtils.isEmpty(czrNewsParam.getId())){
            CzrNews czrNews=czrNewsMapper.selectById(czrNewsParam.getId());
            if(StringUtils.isEmpty(czrNews)){
                return Result.success(201,"无效ID，请检查！");
            }
        }
        CzrNews czrNews=new CzrNews();
        BeanUtils.copyProperties(czrNewsParam, czrNews);
        if(StringUtils.isEmpty(czrNewsParam.getId())){
            czrNews.setViews(0);
            czrNews.setUserId(userId);
        }
//        if(StringUtils.isEmpty(czrNewsParam.getId())) {
            czrNews.setPubTime(format.format(new Date()));
//        }
        this.saveOrUpdate(czrNews);
        return Result.success(200,"提交成功!");
    }

    @Override
    public Result<Object> getNewsInfo(Long newsId) throws Exception {
        TencentCosUtil tencentCosUtil=new TencentCosUtil();
        //查询浏览量
       CzrNews czrNews= this.getById(newsId);
        if(!StringUtils.isEmpty(czrNews)){
            Integer viewsNum= (Integer) czrNews.getViews();
            viewsNum++;
            czrNews.setViews(viewsNum);
            boolean resultBoolean=czrNews.updateById();
            if(resultBoolean){
                CzrNewsVo czrNewsVo=new CzrNewsVo();
                BeanUtils.copyProperties(czrNews, czrNewsVo);
                CzrUser czrUser=czrUserService.getById(czrNews.getUserId());
                if(StringUtils.isEmpty(czrUser)){
                    return Result.fail("服务异常！");
                }
                czrNewsVo.setUserLogo(tencentCosUtil.imgFile_wx(czrUser.getUserLogo()));
                czrNewsVo.setNickName(czrUser.getNickName());
                if (!StringUtils.isEmpty(czrNewsVo.getNewsLogo())) {
                    czrNewsVo.setNewsLogo(tencentCosUtil.imgFile_wx(czrNewsVo.getNewsLogo()));
                }
                if (!StringUtils.isEmpty(czrNewsVo.getWebLogo())) {
                    czrNewsVo.setWebLogo(tencentCosUtil.imgFile_wx(czrNewsVo.getWebLogo()));
                }
                return Result.data(czrNewsVo);
            }else{
                return Result.fail("服务异常！");
            }
        }else{
            return Result.fail("新闻ID不存在，请检查！");
        }
    }

    @Override
    public Result<Object> glList(NewsParam search) throws Exception {

        List<Map<String,Object>> list=czrNewsMapper.getNewsInfoByNewsId(search.getColumnId());

        List<Integer> idList =new ArrayList<>();
        idList.add(search.getColumnId());
        for(Map<String,Object> map:list){
            idList.add(Integer.parseInt(map.get("id").toString()));
        }
        TencentCosUtil tencentCosUtil=new TencentCosUtil();
        Page<CzrNews> page = new Page<>();
        page.setSize(search.getSize());
        page.setCurrent(search.getCurrent());
        LambdaQueryWrapper<CzrNews> ew = new LambdaQueryWrapper<>();
        if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(search.getKeyword())){
            ew.like(CzrNews::getTitle,search.getKeyword());
        }
        ew.in(CzrNews::getColumnId,idList);
        ew.orderByDesc(CzrNews::getPubTime);
        page = this.getBaseMapper().selectPage(page,ew);
        JSONArray array=new JSONArray();
        for (CzrNews czrNews : page.getRecords()) {
            CzrNewsVo czrNewsVo = new CzrNewsVo();
            BeanUtils.copyProperties(czrNews, czrNewsVo);
            //查询用户表
            CzrUser czrUser = czrUserService.getById(czrNews.getUserId());
            if (!StringUtils.isEmpty(czrUser)) {
                czrNewsVo.setNickName(czrUser.getNickName());
                czrNewsVo.setUserLogo(czrUser.getUserLogo());
            }
            if (!StringUtils.isEmpty(czrNewsVo.getNewsLogo())) {
                czrNewsVo.setNewsLogo(czrNewsVo.getNewsLogo());
            }
            if (!StringUtils.isEmpty(czrNewsVo.getWebLogo())) {
                czrNewsVo.setWebLogo(czrNewsVo.getWebLogo());
            }
//            czrNewsVo.setPubTime(DateUtils.getTimeDescriptionByDate(new Date(),czrNewsVo.getPubTime()));
            array.add(czrNewsVo);
        }
        JSONObject object= PageUtil.getPage(array,page);
        return Result.data(object);
    }

    @Override
    public Result<Map<String, Object>> delNews(Integer newsId, JSONObject cacheToken) throws Exception {
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

//        if(!StringUtils.isEmpty(cacheToken) && cacheToken.getInteger("user_type")!=1){
//            return Result.success(201,"非管理员账号，无法删除新闻！");
//        }
        CzrNews czrNews=czrNewsMapper.selectById(newsId);
        if(StringUtils.isEmpty(czrNews)){
            return Result.success(201,"无效ID！");
        }
        int resultBoolean=czrNewsMapper.deleteById(czrNews);
        if(resultBoolean>=0){
            return Result.success(200,"删除成功");
        }else{
            return Result.success(201,"删除失败！");
        }
    }

    @Override
    public Result<Object> getNewsInfoByNewsId(Integer columnId) throws Exception {
        List<Map<String,Object>> list=czrNewsMapper.getNewsInfoByNewsId(columnId);
        JSONArray array=JSONArray.parseArray(JSON.toJSONString(list));
        return Result.data(array);
    }

    @Override
    public Result<Object> addChildColumn(CzrColumn column) throws Exception {

        boolean rs= column.insertOrUpdate();
        if(rs){
            return Result.success(200,"处理成功");
        }else{
            return Result.success(201,"处理失败！");
        }
    }

}
